<script setup lang="ts">
import { sendSms, type SmsType } from '@/views/user/apis';
import { trimBlank } from '@vc/utils';
import { type FormInstance } from 'element-plus';
import { sendEmailSms } from '../apis/profile';
import { isAccountErrCode, isMsgErrCode, pageCfg, rules } from '../config';
import { useVerifyCode } from '../use';

interface Props {
  form: FormInstance;
  /** 手机号 */
  phone: string;
  /** 验证码 */
  verifyCode: string;
  /** 错误信息 */
  errorMess?: string;
  errorAccountMess?: string;
  smsType?: SmsType;
  formvalidateField?: string[]
  showText?: boolean;
  prefixIcon?: string;
}

 const { form, showText, verifyCode, errorMess, phone, prefixIcon, smsType = 'register', formvalidateField = ['account', 'checked'] } = defineProps<Props>();

const emit = defineEmits(['update:verifyCode', 'update:errorAccountMess', 'update:errorMess', 'getSms']);

const isEmail = smsType === 'email';

const { isDisabled, text } = useVerifyCode();

const handleGetSms = async() => {
  form.clearValidate();

  if (formvalidateField?.length) {
    await form.validateField(formvalidateField, async(isValid: boolean) => {
      if (isValid) {
        await sendRequest();
      }
    });
  } else {
    await sendRequest();
  }
};

const sendRequest = async () => {
  await (isEmail ? sendEmailSms : sendSms)(isEmail ?
    { email: trimBlank(phone, 'all') } : {
      phone: trimBlank(phone, 'all'),
      smsType
    })
  .then((res) => {
    if (res.code === 200) {
      form.clearValidate('verifyCode');
      useVerifyCode().start(60);
    } else {
      if (isMsgErrCode.includes(res.code)) {
        emit('update:errorMess', res.msg);
      } else if (isAccountErrCode.includes(res.code)) {
        emit('update:errorAccountMess', res.msg);
      }
    }
  })
  .catch((err) => {
    console.log(err, 777);
    emit('update:errorMess', err.message || err.msg);
  });
};

onBeforeUnmount(() => {
  useVerifyCode().end();
});
</script>

<template>
  <el-form-item prop="verifyCode" :error="errorMess" :rules="rules.phoneCode">
    <div class="w-full flex justify-between align-center">
      <span v-if="showText" class="text-[#666666] text-14px w-100px flex-none">验证码</span>
      <vc-input
        :prefix-icon="prefixIcon"
        type="number"
        maxlength="6"
        :placeholder="pageCfg.codePlaceholder"
        class="h-40px"
        clearable
        :model-value="verifyCode"
        @input="(value) => emit('update:verifyCode', value)"
      />
      <el-button :disabled="isDisabled" class="ml-2 h-40px change-color" @click="handleGetSms">
        {{ text.length > 0 ? text + '秒后重新获取' : pageCfg.getCodeText }}
      </el-button>
    </div>
  </el-form-item>
</template>
<style lang="scss">
:deep(.change-color){
  &:hover{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
  &:focus{
    color: #02C680;
    background-color: rgba(231,247,243,0.3);
    border-color: #02C680;
  }
}
</style>
